import './App.less';
import React from 'react';
import { withRouter } from "react-router-dom";
import { connect } from 'react-redux';
import { message } from "antd";
import { setLoginInfo } from "@/actions";
import MyLayout from '@/components/layout'
import Login from '@/pages/login'
class AppComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    window.reactHistory = this.props.history;
  }
  componentDidMount() {
    if (!this.props.token && this.props.location.pathname !== '/login') {
      this.get("/admin/is-logged", '').then((res) => {
        if (res.code === 200) {
          this.props.setLoginInfo(res.data);
          localStorage.setItem('my-login-token', res.data.token);
          message.success("自动登录成功", 1.5, () => {
            this.props.history.push({
              pathname: "/home",
            });
          });
        } else {
          message.error(res.msg || '自动登录失败', 1.5, () => { this.props.history.push('/login'); })
        }
      })
    }
  }
  componentWillUnmount() {
    this.setState = () => false;
  }
  render() {
    if (this.props.location.pathname === '/login') {
      return <Login  {...this.props} />
    } else {
      return <MyLayout {...this.props} />;
    }
  }
}

const mapStateToProps = state => {
  return {
    count: state.counter.count,
    hello: state.counter.hello,
    token: state.user.token,
    userInfo: state.user.userInfo,
  }
}
// Map Redux actions to component props
const mapDispatchToProps = dispatch => {
  return {
    setLoginInfo: (info) => {
      dispatch(setLoginInfo(info))
    }
  }
}

const App = connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(AppComponent))

export default App
